package fr.labri.macchiato.framework.technical.share;

import com.google.gwt.http.client.URL;
import com.google.gwt.http.client.UrlBuilder;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.user.client.Window.Location;

import fr.labri.macchiato.framework.business.encoder.Encoders;
import fr.labri.macchiato.framework.business.model.project.Project;
import fr.labri.macchiato.framework.business.service.ProjectService;
import fr.labri.macchiato.framework.business.service.Services;
import fr.labri.macchiato.framework.technical.encoder.Encoder;
import fr.labri.macchiato.framework.util.FrameworkException;

/**
 * Class regrouping a set of methods to share a project on different social
 * networks
 * 
 * @author Matthieu FOUCAULT
 * 
 */
public class ShareFunctionalities {

	private static final String ERROR_PARSING_URL = "Une erreur est apparue lors de la récupération du projet partagé";
	private static final String PROJECT_PARAMETER = "proj";
	private static final String MACCHIATO_IMAGE_URL = "http://macchiato.fr/img/macchiato_logo_small.png";

	/**
	 * Shares the project with the given name on facebook. This method encodes
	 * the project in the shared URL, so that is can be loaded later
	 * 
	 * @param projectName
	 */
	public static void shareProjectOnFacebook(String projectName) {

		shareProject(getSharedURL(projectName), MACCHIATO_IMAGE_URL, projectName, projectName,
				projectName);
	}

	private static ProjectService getProjectService() {

		return Services.getInstance().getProjectService();
	}

	private static Encoder<Project> getProjectEncoder() {
		return Encoders.getInstance().getProjectEncoder();
	}

	private static native void shareProject(String link, String picture,
			String name, String caption, String description)/*-{

		$wnd.postToFeed(link, picture, name, caption, description);
	}-*/;

	/**
	 * 
	 * @param projectName
	 * @return the generated URL to share a given project
	 */
	public static String getSharedURL(String projectName) {

		Project project = getProjectService().loadProject(projectName);
		String encodedProject = getProjectEncoder().encode(project);

		UrlBuilder builder = Location.createUrlBuilder();
		builder.removeParameter(PROJECT_PARAMETER);
		builder.setParameter(PROJECT_PARAMETER, URL.encode(encodedProject));
		
		return builder.buildString();
	}

	/**
	 * 
	 * @return The project that has been shared by another user, and which is
	 *         stored in the page URL
	 */
	public static Project getSharedProject() {
		String encodedProject = Location.getParameter(PROJECT_PARAMETER);
		if (encodedProject == null)
			return null;

		encodedProject = URL.decode(encodedProject);
		try {
		Project project = getProjectEncoder().decode(encodedProject);
		return project;
		} catch (JSONException ex) {
			throw new FrameworkException(ERROR_PARSING_URL);
		}

	
	}

}
